package com.hankol.newretail

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import androidx.annotation.NonNull
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.setMallPriceTTF
import com.baselibrary.extension.toast
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.MarginDecoration
import com.baselibrary.activity.BaseActivity
import com.hankol.newretail.adapter.StoreGoodsAdapter
import com.hankol.newretail.adapter.cart.ShopCartGroupAdapter
import com.hankol.newretail.bean.GoodListBean
import com.hankol.newretail.bean.ShopCartBean
import com.hankol.newretail.callback.OnShopCartCallBack
import com.hankol.newretail.databinding.ActivityShopCartBinding
import com.hankol.newretail.viewmodel.ShopCartViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ActivityRouter.NEW_RETAIL.SHOP_CART)
class ShopCartActivity : BaseActivity(), View.OnClickListener, OnShopCartCallBack {
    private var groupPos: Int = -1
    private var childPos: Int = -1
    private var shopType: Int = -1
    private lateinit var viewModel: ShopCartViewModel
    private lateinit var dataBinding: ActivityShopCartBinding
    private val mCartGroupAdapter: ShopCartGroupAdapter by lazy { ShopCartGroupAdapter() }
    private val mRecommendAdapter: StoreGoodsAdapter by lazy { StoreGoodsAdapter() }
    private val shopCartList: ArrayList<ShopCartBean> = arrayListOf()
    private var page = 1
    private var hasnext: Boolean = false
    private var isEmpty = false
    private var lastPosition = 0 //RecyclerView的第一个可视item的position

    private var lastOffset = 0 //与RecyclerView顶部的偏移量


    companion object {
        const val CART_REDUCE = 0x12//购物车减
        const val CART_PLUS = 0x11//购物车加
    }

    override fun getLayoutId(): Int {
        initImmersion(true)
        return R.layout.activity_shop_cart
    }

    override fun onRestart() {
        super.onRestart()
        mCartGroupAdapter.childAdapterList.clear()
        viewModel.reqShopCartList()
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        dataBinding = getDataBinding<ActivityShopCartBinding>()
        viewModel = getActivityViewModelProvider(this).get(ShopCartViewModel::class.java)
//        initData()
        dataBinding.rvShopCart.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(@NonNull recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (dataBinding.rvShopCart.layoutManager != null) {
                    val mLayoutManager = dataBinding.rvShopCart.layoutManager as LinearLayoutManager
                    val topView = mLayoutManager.getChildAt(0) //获取第一个可视的item
                    if (topView != null) {
                        lastOffset = topView.top
                        lastPosition = mLayoutManager.getPosition(topView)
                    }
                }
            }
        })
        initObserver()
        initListener()
    }


    fun initData() {
        mCartGroupAdapter.childAdapterList.clear()
        showLoadingDialog()
        viewModel.reqShopCartList()
    }

    @SuppressLint("NotifyDataSetChanged") fun initObserver() {

        viewModel.shopCartLD.observe(this, Observer {
            showTopTip()
            dataBinding.smartShopCart.finishRefresh()
            hideLoadingDialog()
            dataBinding.smartShopCart.visibility = View.VISIBLE
            if (it.isNotEmpty()) {
                shopCartList.clear()
                shopCartList.addAll(it)
                dataBinding.rvShopCart.adapter = mCartGroupAdapter
                dataBinding.rvShopCart.layoutManager = LinearLayoutManager(this)
                dataBinding.rvShopCart.removeItemDecoration(deco)
                mCartGroupAdapter.setNewData(shopCartList)
                dataBinding.llBottomPriceBuy.visibility = View.VISIBLE
                isEmpty = false
                (dataBinding.rvShopCart.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(lastPosition, lastOffset)
            } else {
                showEmptyView()
            }
            dataBinding.smartShopCart.setEnableLoadMore(isEmpty)
            onComputePriceCall()
        })

        viewModel.delCartShopLD.observe(this, Observer {
            hideLoadingDialog()
            if (it.success) {
                if (groupPos != -1 && childPos != -1) {
                    if (mCartGroupAdapter.childAdapterList[groupPos].data.size > childPos) {
                        mCartGroupAdapter.childAdapterList[groupPos].remove(childPos)
                        if (mCartGroupAdapter.childAdapterList[groupPos].data.size == 0) {
                            mCartGroupAdapter.data.removeAt(groupPos)
                            mCartGroupAdapter.notifyDataSetChanged()
                        }
                        groupPos = -1
                        childPos = -1
                        if (viewModel.isCartEmpty(mCartGroupAdapter)) {
                            showEmptyView()
                        } else {
                            isEmpty = false
                        }
                    }
                }
                onComputePriceCall()
            } else {
                ToastUtils.showShort(applicationContext, "删除失败")
            }
        })

        viewModel.selectCartShopLD.observe(this, Observer {
            hideLoadingDialog()
            if (groupPos != -1 && childPos != -1) {
                if (mCartGroupAdapter.childAdapterList.size > groupPos) {
                    if (mCartGroupAdapter.childAdapterList[groupPos].data.size > childPos) {
                        val selected = mCartGroupAdapter.childAdapterList[groupPos].data[childPos].selected
                        if (selected == 1) {
                            shopCartList[groupPos].mallCartSkuDtoList[childPos].selected = 0
                            mCartGroupAdapter.childAdapterList[groupPos].data[childPos].selected = 0
                        } else {
                            shopCartList[groupPos].mallCartSkuDtoList[childPos].selected = 1
                            mCartGroupAdapter.childAdapterList[groupPos].data[childPos].selected = 1
                        }
                        mCartGroupAdapter.notifyItemChanged(groupPos)
                        mCartGroupAdapter.childAdapterList[groupPos].notifyItemChanged(childPos)
                        groupPos = -1
                        childPos = -1
                        onComputePriceCall()
                    }
                }
            } else {
                //通过店铺勾选的
                onComputePriceCall()
            }
        })

        viewModel.addCartShopLD.observe(this, Observer {
            hideLoadingDialog()
            if (it.success) {
                if (shopType == CART_PLUS) {
                    if (shopCartList.size > groupPos) {
                        if (shopCartList[groupPos].mallCartSkuDtoList.size > childPos) {
                            shopCartList[groupPos].mallCartSkuDtoList[childPos].num += 1
                        }
                    }
                } else {
                    if (shopCartList.size > groupPos) {
                        if (shopCartList[groupPos].mallCartSkuDtoList.size > childPos) {
                            shopCartList[groupPos].mallCartSkuDtoList[childPos].num -= 1
                        }
                    }
                }
                if (it.mallProductGiftCommodityVos != null) {
                    shopCartList[groupPos].mallCartSkuDtoList[childPos].mallProductGiftCommodityVos = it.mallProductGiftCommodityVos
                } else {
                    shopCartList[groupPos].mallCartSkuDtoList[childPos].mallProductGiftCommodityVos = ArrayList()
                }
                mCartGroupAdapter.notifyItemChanged(groupPos)
                mCartGroupAdapter.childAdapterList[groupPos].notifyItemChanged(childPos)
                groupPos = -1
                childPos = -1
                shopType = -1
                onComputePriceCall()
            }
        })

        viewModel.guessYouLikeLD.observe(this, Observer {
            hideLoadingDialog()
            dataBinding.smartShopCart.finishRefresh()
            if (it.data.checkNotNull()) {
                hasnext = it.hasnext
                dataBinding.smartShopCart.finishLoadMore()
                if (page == 1) {
                    mRecommendAdapter.setNewData(it.data)
                } else {
                    mRecommendAdapter.addData(it.data)
                }
                page++
            } else {
                dataBinding.smartShopCart.finishLoadMore()
            }
        })

    }

    private fun showTopTip() {
        val shopCartType = SpUtils.getInt(this, Constants.KEY_CONFIG_SHOP_CART_TYPE, 0)
        // 银行系统原因，暂时只支持单店铺结算
        dataBinding.llTopTip.visibility = if (shopCartType == 0) View.VISIBLE else View.GONE
    }

    val deco by lazy { MarginDecoration(this, 5) }
    private fun showEmptyView() {
        isEmpty = true
        mCartGroupAdapter.setNewData(emptyList())
        dataBinding.tvShopCartSumPrice.text = "0"
        dataBinding.tvShopCartSumPrice.setMallPriceTTF(this)
        dataBinding.tvUnit.setMallPriceTTF(this)
        dataBinding.llBottomPriceBuy.visibility = View.GONE
        viewModel.reqGuessYouLikeGoodList(page)
        mRecommendAdapter.removeAllHeaderView()
        val headView = LayoutInflater.from(applicationContext).inflate(R.layout.layout_shopcart_empty_head, null)
        mRecommendAdapter.addHeaderView(headView)
        dataBinding.rvShopCart.layoutManager = GridLayoutManager(this, 2)
        dataBinding.rvShopCart.removeItemDecoration(deco)
        dataBinding.rvShopCart.addItemDecoration(deco)
        dataBinding.rvShopCart.adapter = mRecommendAdapter
        mRecommendAdapter.setOnItemClickListener { adapter, view, position ->
            if (!DoubleClickHelper.isOnDoubleClick()) {
                val goodListBean = adapter.data[position] as GoodListBean
                //商品详情
                val map = java.util.HashMap<String, Any>()
                map[Constants.GOODS_DETAIL_ID] = goodListBean.id
                map[Constants.GOODS_DETAIL_SOURCE] = "购物车页猜你喜欢"
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.GOODS_DETAUILS, map)
            }
        }
    }

    fun initListener() {
        dataBinding.smartShopCart.setOnRefreshListener {
            groupPos = -1
            childPos = -1
            shopType = -1
            page = 1
            initData()
        }
        dataBinding.smartShopCart.setOnLoadMoreListener {
            if (hasnext) {
                viewModel.reqGuessYouLikeGoodList(page)
            } else {
                dataBinding.smartShopCart.finishLoadMore()
            }
        }
        mCartGroupAdapter.setOnShopCartCallBack(this)
        dataBinding.llSelectAll.setOnClickListener(this)
        dataBinding.ivShopCartBack.setOnClickListener(this)
        dataBinding.tvShopCartSettlement.setOnClickListener(this)
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.iv_shop_cart_back -> finish()
            R.id.ll_select_all -> {
                //全选或者取消选中
                if (dataBinding.llSelectAll.isSelected) {
                    mCartGroupAdapter.unSelectedGroupAll()
                    dataBinding.llSelectAll.isSelected = false
                } else {
                    mCartGroupAdapter.selectedGroupAll()
                    dataBinding.llSelectAll.isSelected = true
                }
                onComputePriceCall()
            }
            R.id.tv_shop_cart_settlement -> {
                //结算
                if (viewModel.getSelectCartIds(mCartGroupAdapter).checkNotNull() && viewModel.getSelectCartIds(mCartGroupAdapter).length != 1) {
                    val shopCartType = SpUtils.getInt(this, Constants.KEY_CONFIG_SHOP_CART_TYPE, 0)
                    if (shopCartType == 0 && viewModel.shopIdList.size != 1) {
                        "银行系统原因，暂时只支持单店铺结算".toast()
                        return
                    }
                    val hashMap: HashMap<String, Any> = hashMapOf()
                    hashMap[ConfirmNewRetailOrderActivity.KEY_CONFIRM_ORDER_CARTIDS] = viewModel.getSelectCartIds(mCartGroupAdapter)
                    ARouterUtils.jump(ActivityRouter.NEW_RETAIL.CONFIRM_ORDER, hashMap)
                }
            }
        }
    }


    @SuppressLint("SetTextI18n") override fun onComputePriceCall() {
        val changePrice = viewModel.changePrice(mCartGroupAdapter)
        val goodsPiece = viewModel.changeGoodsPiece(mCartGroupAdapter)
        dataBinding.tvShopCartSumPrice.text = "${AmountUtil.changeF2YKeepTwo(changePrice.toString())}"
        dataBinding.tvShopCartSumPrice.setMallPriceTTF(this)
        dataBinding.tvUnit.setMallPriceTTF(this)
        if (goodsPiece > 0) {
            dataBinding.tvShopCartSumNum.text = "共${goodsPiece}件｜合计："
            dataBinding.tvShopCartSettlement.isEnabled = true
            dataBinding.tvShopCartSettlement.setBackgroundResource(R.drawable.shape_f54d53_solid_20dp)
        } else {
            dataBinding.tvShopCartSumNum.text = "共${0}件｜合计："
            dataBinding.tvShopCartSettlement.isEnabled = false
            dataBinding.tvShopCartSettlement.setBackgroundResource(R.drawable.shape_f54d53_alpha50_solid_20dp)
        }
        dataBinding.tvShopCartSettlement.visibility = View.VISIBLE
    }

    override fun delChildShop(groupPos: Int, childPos: Int) {
        this.groupPos = groupPos
        this.childPos = childPos
        if (mCartGroupAdapter.childAdapterList.size > groupPos) {
            if (mCartGroupAdapter.childAdapterList[groupPos].data.size > childPos) {
                showLoadingDialog()
                val cartId = mCartGroupAdapter.childAdapterList[groupPos].data[childPos].cartId
                viewModel.reqDelCartShop("[${cartId}]")
            }
        }
    }

    override fun onChildShopSelect(groupPos: Int, childPos: Int) {
        this.groupPos = groupPos
        this.childPos = childPos
        if (mCartGroupAdapter.childAdapterList.size > groupPos) {
            if (mCartGroupAdapter.childAdapterList[groupPos].data.size > childPos) {
                val cartId = mCartGroupAdapter.childAdapterList[groupPos].data[childPos].cartId
                val selected = mCartGroupAdapter.childAdapterList[groupPos].data[childPos].selected
                showLoadingDialog()
                if (selected == 1) {
                    //执行取消选中
                    viewModel.reqSelectCartShop("[${cartId}]", 0)
                } else {
                    //执行选中
                    viewModel.reqSelectCartShop("[${cartId}]", 1)
                }
            }
        }
    }

    override fun onGroupSelect(isSelected: Boolean, position: Int) {
        showLoadingDialog()
        val cartIds = viewModel.setSelectAllCartIds(mCartGroupAdapter, position, isSelected)
        viewModel.reqSelectCartShop(cartIds, if (isSelected) 1 else 0)
    }

    override fun onShopReduce(groupPos: Int, childPos: Int) {
        this.groupPos = groupPos
        this.childPos = childPos
        shopType = CART_REDUCE
        if (mCartGroupAdapter.childAdapterList.size > groupPos) {
            if (mCartGroupAdapter.childAdapterList[groupPos].data.size > childPos) {
                if (mCartGroupAdapter.childAdapterList[groupPos].data[childPos].num <= 1) {
                    ToastUtils.showShort(applicationContext, "最少购买1件")
                } else {
                    showLoadingDialog()
                    val skuId = mCartGroupAdapter.childAdapterList[groupPos].data[childPos].skuId
                    viewModel.reqAddCartShop(skuId, -1)
                }
            }
        }
    }

    override fun onShopPlus(groupPos: Int, childPos: Int) {
        shopType = CART_PLUS
        showLoadingDialog()
        this.groupPos = groupPos
        this.childPos = childPos
        if (mCartGroupAdapter.childAdapterList.size > groupPos) {
            if (mCartGroupAdapter.childAdapterList[groupPos].data.size > childPos) {
                val skuId = mCartGroupAdapter.childAdapterList[groupPos].data[childPos].skuId
                viewModel.reqAddCartShop(skuId, 1)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_pay_success || messageBus.codeType == MessageBus.msgId_commit_order_success || messageBus.codeType == MessageBus.msgId_order_cancel_success) {
            //提交订单、支付成功 刷新购物车
            initData()
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}